//
//  Moya_Extension.swift
//  MM2
//
//  Created by 李成明 on 2022/1/3.
//

import Moya
import SwiftyJSON
import Foundation

//请求超时设置
let requestTimeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<BaseApi>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 20
        done(.success(request))
    } catch {
        return
    }
}

class  MoyaNetwork : NSObject {
    public static func request<T: TargetType>(provider: MoyaProvider<T>,
                               target: T,
                            success successCallback: @escaping ((JSON, String) -> Void),
                            error errorCallback: ((Int, String) -> Void)?,
                            failure failureCallback: ((MoyaError) -> Void)?) {
        provider.request(target) { (result) in
            switch result {
            case .success(let response):
                do {
                    let jsonStr = String(data: response.data, encoding: String.Encoding.utf8)
                    print(jsonStr)
                    let json = try JSON(response.filterSuccessfulStatusCodes().mapJSON())
                    successCallback(json, jsonStr ?? "")
                    
                } catch  {
                    errorCallback?(1, "出现错误")
                }
                break
                
            case .failure(let error):
                
                failureCallback?(error)
                break
                
            }
        }
    }
    
    public static func request<T: TargetType>(target: T,
                               success successCallback:@escaping ((JSON, String) -> Void),
                               error errorCallback: ((Int, String) -> Void)? = nil,
                               failure failureCallback: ((MoyaError) -> Void)? = nil) {
        
        let provider = MoyaProvider<T>(requestClosure: requestTimeoutClosure)
        request(provider: provider, target: target, success: successCallback, error: errorCallback, failure: failureCallback)
    }
}
